<template>
  <div class="common-layout">
    <el-container>
      <el-aside width="200px" style="min-height: 100vh; background-color: rgb(22,46,86)">
        <div class="aside-head-info"
             style="width: 200px; height: 80px; align-items: center; justify-items: center; display: flex">
          <span
              style="color: #f9f9f9; display: flex; align-items: center; justify-content: center; width: 200px">欢迎您，食堂管理员</span>
        </div>
        <el-menu style="border: none" :default-active="currentUrl" router background-color="#162E56"
                 text-color="#f9f9f9">
          <el-menu-item index="/restaurant-manager/index">
            <template #title>
              <el-icon>
                <User/>
              </el-icon>
              用户首页
            </template>
          </el-menu-item>
          <el-menu-item index="/restaurant-manager/restaurant-info-maintain">
            <template #title>
              <el-icon>
                <DishDot/>
              </el-icon>
              餐厅信息
            </template>
          </el-menu-item>
          <el-menu-item index="/restaurant-manager/dishes-maintain">
            <template #title>
              <el-icon>
                <Edit/>
              </el-icon>
              菜品维护
            </template>
          </el-menu-item>
          <el-menu-item index="/restaurant-manager/report-reply">
            <template #title>
              <el-icon>
                <Warning/>
              </el-icon>
              投诉回复
            </template>
          </el-menu-item>
          <el-menu-item index="/restaurant-manager/remark-reply">
            <template #title>
              <el-icon>
                <Message/>
              </el-icon>
              评论回复
            </template>
          </el-menu-item>
          <el-menu-item index="/restaurant-manager/recommend-dish-publish">
            <template #title>
              <el-icon>
                <More/>
              </el-icon>
              新品发布
            </template>
          </el-menu-item>
          <el-menu-item index="/restaurant-manager/vote">
            <template #title>
              <el-icon>
                <Collection/>
              </el-icon>
              调查发布
            </template>
          </el-menu-item>
        </el-menu>
      </el-aside>
      <el-container>
        <el-header
            style="box-shadow: 2px 0 6px rgba(0, 21, 41, .36); display: flex; align-items: center; justify-content: space-between">
          <el-breadcrumb :separator-icon="ArrowRight">
            <el-breadcrumb-item v-for="item in route.matched" :to="{path: item.path}">{{ item.meta.title }}
            </el-breadcrumb-item>

          </el-breadcrumb>
          <div class="avatar-container" style="align-items: center; display: flex; justify-content: flex-end">
            <el-dropdown style="display: flex; align-items: center; justify-content: flex-end" placement="bottom">
        <span class="el-dropdown-link"
              style="display: flex; align-items: center;">
          <el-avatar :size="24" :src="avatarSrc" style="margin: 0 5px"/>
          {{ '欢迎您，' + nickname }}
        </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>个人中心</el-dropdown-item>
                  <el-dropdown-item>退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>
        <el-main>
          <el-form :model="queryParams" ref="queryForm" size="default" :inline="true" label-width="68px">
            <el-form-item label="调查标题" prop="surveyTitle">
              <el-input
                  v-model="queryParams.surveyTitle"
                  placeholder="请输入调查标题"
                  clearable
                  @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="Search" size="default" @click="handleQuery">搜索</el-button>
              <el-button :icon="Refresh" size="default" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <el-row>
            <el-col :span="3">
              <el-button type="primary" :icon="Plus" @click="publishNewSurvey">发布新调查</el-button>
            </el-col>
          </el-row>
          <el-table :data="tableData" v-loading="tableLoading">
            <el-table-column label="调查id" v-if="false" prop="surveyId"/>
            <el-table-column label="调查标题" align="center" prop="surveyTitle"/>
            <el-table-column label="操作" align="center">
              <template #default="scope">
                <el-button link type="primary" :icon="Delete" @click="handleSurveyDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-dialog v-model="addDialogVis" :title="addDialogTitle" width="500px" append-to-body>
            <el-form
                ref="formRef"
                :model="dynamicValidateForm"
                label-width="80px"
                class="demo-dynamic"
            >
              <el-form-item
                  prop="title"
                  label="调查标题"
                  :rules="[
        {
          required: true,
          message: '标题不能为空！',
          trigger: 'blur',
        },
        // {
        //   type: 'email',
        //   message: 'Please input correct email address',
        //   trigger: ['blur', 'change'],
        // },
      ]"
              >
                <el-input v-model="dynamicValidateForm.title"/>
              </el-form-item>
              <el-form-item
                  v-for="(domain, index) in dynamicValidateForm.domains"
                  :key="domain.key"
                  :label="'问题' + (index+1)"
                  :prop="'domains.' + (index) + '.value'"
                  :rules="{
        required: true,
        message: '问题不能为空！',
        trigger: 'blur',
      }"
              >
                <el-input v-model="domain.value"/>
                <el-button class="mt-2" @click.prevent="removeDomain(domain)"
                >删除
                </el-button
                >
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitForm(formRef)">提交</el-button>
                <el-button @click="addDomain">添加新问题</el-button>
                <el-button @click="resetForm(formRef)">重置表单</el-button>
              </el-form-item>
            </el-form>
          </el-dialog>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import {useRoute} from "vue-router";
import {ArrowRight, Search, Refresh, Plus, Delete} from "@element-plus/icons-vue";
import {getLocalStorage, KEY_AVATAR, KEY_NICKNAME, KEY_RESTAURANT_ID} from "../../utils/localStorge.js";
import {baseStaticRecourseAPI, NOW_ENVIRONMENT} from "../../baseAPIConfig";
import {handleDataSubmitWithBlob} from "../../utils/dongyan.js";
import {querySurveyList, querySurveyItem, addSurvey, deleteSurvey} from "../../web-api/resaurant-manager/vote.js";
import {ElMessage, ElMessageBox} from "element-plus";

// 记录当前路由
let currentUrl = ref()

// 记录当前登录用户昵称
let nickname = ref(getLocalStorage(KEY_NICKNAME))

// 记录当前用户登陆的食堂id
let restaurantId = getLocalStorage(KEY_RESTAURANT_ID);

// 记录当前登录用户头像，后期应该要大改
let avatarSrc = baseStaticRecourseAPI[NOW_ENVIRONMENT] + getLocalStorage(KEY_AVATAR)
// 查询表单相关
let queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  surveyTitle: null,
  restaurantId: restaurantId
})
let queryForm = ref()
const restQueryForm = (queryFormRef)=>{
  if(!queryFormRef.value){
    return
  }
  queryFormRef.value.resetFields()
  queryParams.restaurantId = restaurantId
  queryParams.pageNum = 1;
  queryParams.pageSize = 20;
}
const handleQuery = ()=>{
  queryParams.pageNum = 1;
  getList();
}
const resetQuery = ()=>{
  restQueryForm(queryForm)
  getList()
}
const handleSurveyDelete = (row)=>{
  ElMessageBox.confirm(`确定要删除调查"${row.surveyTitle}"`, "警告", {
    cancelButtonText: "取消",
    confirmButtonText: "确定"
  }).then(()=>{
    deleteSurvey(row.surveyId).then(res=>{
      ElMessage.success("删除成功！")
      getList()
    }).catch(err=>console.log(err))
  }).catch(()=>{
    ElMessage.info("删除取消")
  })
}

// 主体数据表格相关
let tableLoading = ref(false)
let tableData = ref([])
let total = ref(0)
const getList = ()=>{
  tableLoading.value = true
  querySurveyList(queryParams).then(res=>{
    tableData.value = res.rows
    total.value = parseInt(res.total)
    tableLoading.value = false
  })
}


// 动态表单相关
let formRef = ref();
const publishNewSurvey = ()=>{
  addDialogTitle.value= "发布调查"
  addDialogVis.value = true
  resetForm(formRef)
}
const dynamicValidateForm = reactive({
  domains: [
    {
      key: 1,
      value: '',
    },
  ],
  title: '',
})
const removeDomain = (item) => {
  const index = dynamicValidateForm.domains.indexOf(item)
  if (index !== -1) {
    dynamicValidateForm.domains.splice(index, 1)
  }
}
const addDomain = () => {
  dynamicValidateForm.domains.push({
    key: Date.now(),
    value: '',
  })
}
const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      // console.log('submit!')
      console.log(dynamicValidateForm)
      let formData = new FormData()
      formData.append("survey", handleDataSubmitWithBlob({
        surveyTitle: dynamicValidateForm.title,
        restaurantId: restaurantId
      }))
      formData.append("sub", handleDataSubmitWithBlob(dataWash(dynamicValidateForm)))
      addSurvey(formData).then(res=>{
        addDialogVis.value = false;
        getList()
      })
    } else {
      // console.log('error submit!')
      return false
    }
  })
}
const resetForm = (formEl) => {
  if (!formEl.value) return
  formEl.value.resetFields()
}
const dataWash = (reactiveEl)=>{
  let ret = []
  for (let i = 0; i < reactiveEl.domains.length; i++) {
    ret.push({surveyLine: reactiveEl.domains[i].value})
  }
  return ret;
}


// 对话框
let addDialogVis = ref(false);
let addDialogTitle = ref("")

let route = useRoute();

// 记录当前食堂管理员属于哪个食堂
// let diningHall = ref('');



onMounted(() => {
  currentUrl.value = route.path;
  getList()
})
</script>

<style scoped>
.is-active {
  color: #f9f9f9 !important;
  background-color: #47739a;
  border-radius: 20px;
  margin: 0 10px;
}

.el-menu-item {
  margin: 5px 10px !important;
}

.el-menu-item:hover {
  border-radius: 20px;
}
</style>